<!--
  * 客户信息表
  *
  * @Author:    lmabbe
  * @Date:      2025-06-24 14:55:52
  * @Copyright  lmabbe
-->
<template>
  <a-modal
    :destroyOnClose="true"
    :maskClosable="false"
    :open="visibleFlag"
    :title="form.customerCode ? '编辑' : '添加'"
    :width="450"
    @cancel="onClose"
  >
    <a-form ref="formRef" :label-col="{ span: 5 }" :model="form" :rules="rules">
      <a-form-item label="客户编号" name="customerCode">
        <a-input v-model:value="form.customerCode" placeholder="客户编号" style="width: 100%" />
      </a-form-item>
      <a-form-item label="客户名称" name="customerName">
        <a-input v-model:value="form.customerName" placeholder="客户名称" style="width: 100%" />
      </a-form-item>
      <a-form-item label="客户简称" name="customerAbbreviation">
        <a-input v-model:value="form.customerAbbreviation" placeholder="客户简称" style="width: 100%" />
      </a-form-item>
      <a-form-item label="客户地址" name="customerAddress">
        <a-input v-model:value="form.customerAddress" placeholder="客户地址" style="width: 100%" />
      </a-form-item>
      <a-form-item label="联系方式" name="contactInformationJson">
        <a-space v-for="(user, index) in form.contactInformationJson" :key="index" align="baseline" style="display: flex; margin-bottom: 8px">
          <a-form-item :name="['contactInformationJson', index, 'contactName']" :rules="{ required: true, message: '联系人必填' }">
            <a-input v-model:value="user.contactName" placeholder="联系人" />
          </a-form-item>
          <a-form-item :name="['contactInformationJson', index, 'contactPhone']" :rules="{ required: true, message: '联系人电话必填' }">
            <a-input v-model:value="user.contactPhone" placeholder="联系电话" />
          </a-form-item>
          <a-form-item :name="['contactInformationJson', index, 'contactPosition']">
            <a-input v-model:value="user.contactPosition" placeholder="联系人职位" />
          </a-form-item>
          <MinusCircleOutlined @click="removeUser(user)" />
        </a-space>
        <a-form-item>
          <a-button type="dashed" block @click="addUser">
            <PlusOutlined />
            添加联系人
          </a-button>
        </a-form-item>
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="备注" style="width: 100%" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry'; // ------------------------ 事件 ------------------------

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  const addFlag = ref(false);

  function show(rowData) {
    addFlag.value = !Object.prototype.hasOwnProperty.call(rowData, 'customerCode');
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    if (!addFlag.value) {
      form.contactInformationJson = JSON.parse(form.contactInformation);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    customerCode: undefined, //客户编号
    customerName: undefined, //客户名称
    customerAbbreviation: undefined, //客户简称
    customerAddress: undefined, //客户地址
    contactInformation: '', //联系方式
    contactInformationJson: [], //联系方式
    remark: undefined, //备注
  };

  let form = reactive({ ...formDefault });

  const rules = {
    customerCode: [{ required: true, message: '客户编号 必填' }],
    customerAbbreviation: [{ required: true, message: '客户简称 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      form.contactInformation = JSON.stringify(form.contactInformationJson);
      if (!addFlag.value) {
        await customerInfoApi.update(form);
      } else {
        await customerInfoApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  function addUser() {
    form.contactInformationJson.push({
      contactName: '',
      contactPhone: '',
      contactPosition: '',
    });
  }

  function removeUser(data) {
    form.contactInformationJson.splice(form.contactInformationJson.indexOf(data), 1);
  }

  defineExpose({
    show,
  });
</script>
